package com.Txunda.fxw.ui;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.Txunda.fxw.R;
import com.Txunda.fxw.base.utils.tool.AppManager;
import com.Txunda.fxw.base.utils.util.JSONUtils;
import com.Txunda.fxw.base.utils.util.MapUtils;
import com.Txunda.fxw.ui.base.BaseAty;
import com.Txunda.fxw.ui.fgt.Business2Fgt;
import com.Txunda.fxw.ui.fgt.BusinessFgt;
import com.Txunda.fxw.ui.fgt.HomeFgt;
import com.Txunda.fxw.ui.fgt.Law2Fgt;
import com.Txunda.fxw.ui.http.AboutUs;
import com.Txunda.fxw.ui.toolkit.util.PreferenceUtil;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationClientOption.AMapLocationProtocol;
import com.amap.api.location.AMapLocationListener;

import java.util.Map;

import butterknife.BindView;

public class MainActivity extends BaseAty implements AMapLocationListener, OnCheckedChangeListener {

    @BindView(R.id.fl_home)
    FrameLayout flHome;
    @BindView(R.id.view_home_aty)
    View viewHomeAty;
    @BindView(R.id.rb_home)
    RadioButton rbHome;
    @BindView(R.id.rb_law)
    RadioButton rbLaw;
    @BindView(R.id.rb_business)
    RadioButton rbBusiness;
    @BindView(R.id.main_rg)
    RadioGroup mainRg;
    /**
     * 第一步:高德定位，获取经纬度
     */

    // 声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;

    private AboutUs aboutUs;
    private long firstTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initLocation();
        mainRg.setOnCheckedChangeListener(this);
        mainRg.check(R.id.rb_home);
        aboutUs.logo(this);
        if (Build.VERSION.SDK_INT >= 23) {
            showContacts();
        }
    }

    @Override
    protected int getFragmentContainerId() {
        return R.id.fl_home;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main2;
    }

    @Override
    public void onCheckedChanged(RadioGroup arg0, int arg1) {
        switch (arg1) {
            case R.id.rb_home://首页
                addFragment(HomeFgt.class, null);
                break;
            case R.id.rb_law://法律
                addFragment(Law2Fgt.class, null);
                break;
            case R.id.rb_business://汽车租赁
//                addFragment(BusinessFgt.class, null);
                addFragment(Business2Fgt.class, null);
                break;
            default:
        }
    }

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - firstTime < 3000) {
            AppManager.getInstance().killAllActivity();
        } else {
            firstTime = System.currentTimeMillis();
            showToast("再按一次返回键退出");
        }
    }

    @Override
    public void onComplete(String requestUrl, String jsonStr) {
        super.onComplete(requestUrl, jsonStr);
        if (requestUrl.contains("logo")) { // 公司logo
            Map<String, String> map = JSONUtils.parseKeyAndValueToMap(jsonStr);
            if (!MapUtils.isEmpty(map) && "success".equals(map.get("flag"))) {
                String data = map.get("data"); // 公司logo
                PreferenceUtil.write(getApplicationContext(), PreferenceUtil.sp_logo, data); // 保存公司logo信息
            }
        }
    }

    @Override
    protected void initialized() {
        aboutUs = new AboutUs();
    }

    @Override
    protected void requestData() {

    }

    /**
     * 第二步初始化定位
     */
    public void initLocation() {
        // 初始化定位
        mLocationClient = new AMapLocationClient(this);
        // 设置定位监听
        mLocationClient.setLocationListener(this);

        // 设置定位参数
        mLocationClient.setLocationOption(getDefaultOption());
        // 启动定位
        startLocation();

    }

    /**
     * ----------------------------------------纬度第三步 设置定位参数-
     *
     * @return AMapLocationClientOption
     */
    private AMapLocationClientOption getDefaultOption() {
        // TODO Auto-generated method stub
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationMode.Hight_Accuracy);// 可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);// 可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);// 可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(2000);// 可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);// 可选，设置是否返回逆地理地址信息。默认是ture
        mOption.setOnceLocation(true);// 可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);// 可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationProtocol.HTTP);// 可选，
        return mOption;
    }

    /**
     * ----------------------------------------第四步 开始定位-
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void startLocation() {

        // 启动定位
        mLocationClient.startLocation();
    }

    // ----------------------------------------第五步 定位监听-
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            /*
             * 解析定位结果
             *
             * 经度
             *
             * 纬度
             */
            if (amapLocation.getErrorCode() == 0) {
                // 定位成功回调信息,设置相关消息
                amapLocation.getLocationType(); // 获取当前定位结果来源
                amapLocation.getLatitude(); // 获取维度
                amapLocation.getLongitude(); // 获取经度
                amapLocation.getAccuracy(); // 获取精度信息
                amapLocation.getDistrict();

                AMapLocation location = mLocationClient.getLastKnownLocation();
                String city = location.getCity();
                // 保存本地数据
                PreferenceUtil.write(getApplicationContext(), PreferenceUtil.sp_mode, city);
                // 保存精度纬度
                PreferenceUtil.write(getApplicationContext(), PreferenceUtil.sp_lat, amapLocation.getLatitude() + "");
                PreferenceUtil.write(getApplicationContext(), PreferenceUtil.sp_lnt, amapLocation.getLongitude() + "");
                // 保存当前地区
                PreferenceUtil.write(getApplicationContext(), PreferenceUtil.sp_district, amapLocation.getDistrict());

            } else {
                Toast.makeText(MainActivity.this, "定位失败！", Toast.LENGTH_SHORT).show();
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mLocationClient) {
            mLocationClient.onDestroy();
            mLocationClient = null;
        }
    }
    private void showContacts() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
//            Toast.makeText(getApplicationContext(), "没有权限,请手动开启定位权限", Toast.LENGTH_SHORT).show();
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
            }, 100);
        } else {
        }
    }

}
